package yijy.printRecognition;

/**
 * Created by rain-hms on 2017/6/8.
 */

//import com.sun.deploy.net.HttpUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import util.HttpUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * A阿里云-数据服务_5_1_身份证识别
 * @author 张绪定
 *
 */
public class AliOcrIdcard {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        AliOcrIdcard aliOcrIdcard=new AliOcrIdcard();
        System.out.println("===================身份证正面信息===================");
        aliOcrIdcard.getAliOcrIdcard("D:/搜狗高速下载/身份证正面.png", "face");
        System.out.println("===================身份证反面信息===================");
//        aliOcrIdcard.getAliOcrIdcard("d://身份证反面.png", "back");
    }

    /**
     * 获取 A阿里云-数据服务_5_1_身份证识别,得到身份证基本信息
     * @return
     */
    public void getAliOcrIdcard(String imgFile,String configStr){

        String host = "http://dm-51.data.aliyun.com";
        String path = "/rest/160601/ocr/ocr_idcard.json";
        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE "+"your APPCODE");
        Map<String, String> querys = new HashMap<String, String>();

        String body=getJosnStrRequestBody(getStrImgBase64(imgFile),configStr);

        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, body);
            String result=EntityUtils.toString(response.getEntity());
            JSONObject resultObj = new JSONObject(result);
            JSONArray outputArray = resultObj.getJSONArray("outputs");
            String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue"); // 取出结果json字符串
            JSONObject out = new JSONObject(output);
            if (out.getBoolean("success")) {

                if(!configStr.isEmpty()&&configStr.equals("face")){
                    String addr = out.getString("address"); // 获取地址
                    String configstr = out.getString("config_str"); // 获取身份证正反面face/side
                    String name = out.getString("name"); // 获取名字
                    String num = out.getString("num"); // 获取身份证号
                    String sex = out.getString("sex"); // 获取性别
                    String birth = out.getString("birth"); // 获取身份证号
                    String nationality = out.getString("nationality"); // 获取民族
                    boolean success = out.getBoolean("success"); // 获取识别结果
                    System.out.printf("addr : %s \n configstr : %s \n  name : %s \n num : %s \n sex : %s\n birth : %s\n nationality : %s\n",
                            addr, configstr, name,num, sex, birth,nationality);
                }

                if(!configStr.isEmpty()&&configStr.equals("back")){
                    String configstr = out.getString("config_str"); // 获取身份证正反面face/side
                    String startdate = out.getString("start_date"); //获取有效期起始时间
                    String enddate = out.getString("end_date"); // 获取有效期结束时间
                    String issue = out.getString("issue"); // 获取签发机关
                    boolean success = out.getBoolean("success"); // 获取识别结果
                    System.out.printf(" configstr : %s \n startdate : %s\n enddate : %s\n issue : %s\n ", configstr, startdate, enddate,issue);
                }

            } else {
                System.out.println("predict error");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 获取身份证图片Base64流
     * String  imgFile explame "d://idcard_example.jpg";
     * @return
     */
    public static String getStrImgBase64(String imgFile){
        // 对图像进行base64编码
        String strImgBase64 = "";
        try {
            File file = new File(imgFile);
            byte[] content = new byte[(int) file.length()];
            FileInputStream finputstream = new FileInputStream(file);
            finputstream.read(content);
            finputstream.close();
            strImgBase64 = new String(Base64.encodeBase64(content));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  strImgBase64;
    }

    /**
     * 获取"身份证识别"请求报文Body(Josn格式的String串)
     * strImgBase64:
     * configStr:示上传图片是身份证正面/反面图像， "face" 表示正面,"back"表示反面
     */
    public static String getJosnStrRequestBody(String strImgBase64,String configStr){
        // 拼装请求body的json字符串
        JSONObject requestObj = new JSONObject();
        try {
            JSONObject configObj = new JSONObject();
            JSONObject obj = new JSONObject();
            JSONArray inputArray = new JSONArray();
            //表示上传图片是身份证正面/反面图像， “face” 表示正面，”back”表示反面
            configObj.put("side", configStr);
            obj.put("image", getParam(50, strImgBase64));
            obj.put("configure", getParam(50, configObj.toString()));
            inputArray.put(obj);
            requestObj.put("inputs", inputArray);;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String requestBody = requestObj.toString();
        return requestBody;
    }

    /**
     * 获取参数的json对象
     */
    public  static JSONObject getParam(int type, String dataValue) {
        JSONObject obj = new JSONObject();
        try {
            obj.put("dataType", type);
            obj.put("dataValue", dataValue);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return obj;
    }


}
